/**
 * 3D立体条形图可视化器
 */
class ThreeDBarVisualizer extends VisualizerInterface {
    constructor(canvas, ctx) {
        super(canvas, ctx);
        this.rotationX = 0;
        this.rotationY = 0;
        this.rotationZ = 0;
        this.bars = [];
    }

    getInfo() {
        return {
            name: '3D Bars',
            description: '3D立体条形图频谱可视化',
            author: 'AudioNN',
            version: '1.0.0',
            category: '3d'
        };
    }

    getDefaultSettings() {
        return {
            ...super.getDefaultSettings(),
            barCount: 64,
            rotationSpeed: 0.01,
            perspective: 800,
            autoRotate: true,
            barSpacing: 1.2,
            maxHeight: 200,
            lightingEffect: true
        };
    }

    init(config = {}) {
        super.init(config);
        this.initializeBars();
        return this;
    }

    initializeBars() {
        this.bars = [];
        const gridSize = Math.ceil(Math.sqrt(this.settings.barCount));
        
        for (let x = 0; x < gridSize; x++) {
            for (let z = 0; z < gridSize; z++) {
                if (this.bars.length < this.settings.barCount) {
                    this.bars.push({
                        x: (x - gridSize / 2) * this.settings.barSpacing,
                        y: 0,
                        z: (z - gridSize / 2) * this.settings.barSpacing,
                        height: 0,
                        color: { r: 100, g: 150, b: 255 },
                        index: this.bars.length
                    });
                }
            }
        }
    }

    render(frequencyData, cachedData = null, currentTime = 0) {
        this.clearCanvas();
        
        const dataToUse = cachedData || frequencyData;
        if (!dataToUse) return;

        const width = this.canvas.width / window.devicePixelRatio;
        const height = this.canvas.height / window.devicePixelRatio;

        // 更新旋转
        if (this.settings.autoRotate) {
            this.rotationY += this.settings.rotationSpeed;
            this.rotationX = Math.sin(currentTime * 0.001) * 0.3;
        }

        // 更新条形高度
        this.updateBars(dataToUse);

        // 绘制3D场景
        this.draw3DScene(width, height);
    }

    updateBars(frequencyData) {
        const dataPerBar = frequencyData.length / this.bars.length;
        
        this.bars.forEach((bar, index) => {
            const dataIndex = Math.floor(index * dataPerBar);
            const intensity = frequencyData[dataIndex] / 255;
            
            bar.height = intensity * this.settings.maxHeight;
            
            // 更新颜色
            const hue = (index / this.bars.length) * 360;
            const rgb = this.hslToRgb(hue, 80, 50 + intensity * 30);
            bar.color = { r: rgb[0], g: rgb[1], b: rgb[2] };
        });
    }

    draw3DScene(width, height) {
        const centerX = width / 2;
        const centerY = height / 2;
        
        // 排序条形以正确绘制深度
        const sortedBars = [...this.bars].sort((a, b) => {
            const aZ = this.transform3D(a.x, a.y, a.z).z;
            const bZ = this.transform3D(b.x, b.y, b.z).z;
            return bZ - aZ; // 远的先画
        });

        sortedBars.forEach(bar => {
            this.draw3DBar(bar, centerX, centerY);
        });
    }

    draw3DBar(bar, centerX, centerY) {
        // 变换3D坐标到2D
        const bottom = this.transform3D(bar.x, 0, bar.z);
        const top = this.transform3D(bar.x, bar.height, bar.z);
        
        const bottomScreen = this.project3D(bottom, centerX, centerY);
        const topScreen = this.project3D(top, centerX, centerY);
        
        if (bottomScreen.z < 0 || topScreen.z < 0) return; // 在相机后面
        
        const barWidth = 20 / (1 + bottom.z * 0.001); // 透视缩放
        
        // 计算光照
        const lightIntensity = this.calculateLighting(bar);
        
        // 绘制条形的顶面
        this.drawBarTop(topScreen.x, topScreen.y, barWidth, bar.color, lightIntensity);
        
        // 绘制条形的侧面
        this.drawBarSides(bottomScreen, topScreen, barWidth, bar.color, lightIntensity);
        
        // 绘制条形的前面
        this.drawBarFront(bottomScreen, topScreen, barWidth, bar.color, lightIntensity);
    }

    transform3D(x, y, z) {
        // 应用旋转变换
        let newX = x;
        let newY = y;
        let newZ = z;
        
        // Y轴旋转
        const cosY = Math.cos(this.rotationY);
        const sinY = Math.sin(this.rotationY);
        const tempX = newX * cosY - newZ * sinY;
        newZ = newX * sinY + newZ * cosY;
        newX = tempX;
        
        // X轴旋转
        const cosX = Math.cos(this.rotationX);
        const sinX = Math.sin(this.rotationX);
        const tempY = newY * cosX - newZ * sinX;
        newZ = newY * sinX + newZ * cosX;
        newY = tempY;
        
        return { x: newX, y: newY, z: newZ };
    }

    project3D(point3D, centerX, centerY) {
        const z = point3D.z + 5; // 避免除零
        const scale = this.settings.perspective / (this.settings.perspective + z);
        
        return {
            x: centerX + point3D.x * scale,
            y: centerY - point3D.y * scale,
            z: z
        };
    }

    calculateLighting(bar) {
        if (!this.settings.lightingEffect) return 1;
        
        // 简单的光照计算
        const lightDirection = { x: 0.5, y: 1, z: 0.5 };
        const normal = { x: 0, y: 1, z: 0 }; // 顶面法向量
        
        const dot = normal.x * lightDirection.x + 
                   normal.y * lightDirection.y + 
                   normal.z * lightDirection.z;
        
        return Math.max(0.3, dot);
    }

    drawBarTop(x, y, size, color, lighting) {
        this.ctx.fillStyle = `rgb(${Math.floor(color.r * lighting)}, ${Math.floor(color.g * lighting)}, ${Math.floor(color.b * lighting)})`;
        this.ctx.fillRect(x - size / 2, y - size / 2, size, size);
    }

    drawBarSides(bottom, top, size, color, lighting) {
        const sideColor = {
            r: Math.floor(color.r * lighting * 0.7),
            g: Math.floor(color.g * lighting * 0.7),
            b: Math.floor(color.b * lighting * 0.7)
        };
        
        this.ctx.fillStyle = `rgb(${sideColor.r}, ${sideColor.g}, ${sideColor.b})`;
        
        // 绘制右侧面
        this.ctx.beginPath();
        this.ctx.moveTo(bottom.x + size / 2, bottom.y);
        this.ctx.lineTo(top.x + size / 2, top.y);
        this.ctx.lineTo(top.x + size / 2, top.y + size / 2);
        this.ctx.lineTo(bottom.x + size / 2, bottom.y + size / 2);
        this.ctx.closePath();
        this.ctx.fill();
    }

    drawBarFront(bottom, top, size, color, lighting) {
        const frontColor = {
            r: Math.floor(color.r * lighting * 0.9),
            g: Math.floor(color.g * lighting * 0.9),
            b: Math.floor(color.b * lighting * 0.9)
        };
        
        this.ctx.fillStyle = `rgb(${frontColor.r}, ${frontColor.g}, ${frontColor.b})`;
        
        // 绘制前面
        this.ctx.fillRect(
            bottom.x - size / 2,
            top.y,
            size,
            bottom.y - top.y
        );
        
        // 添加边框
        this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.2)';
        this.ctx.lineWidth = 1;
        this.ctx.strokeRect(
            bottom.x - size / 2,
            top.y,
            size,
            bottom.y - top.y
        );
    }

    resize(width, height) {
        // 3D场景不需要特殊的resize处理
    }
}

// 注册可视化器到全局注册表
if (typeof window !== 'undefined') {
    if (!window.visualizerRegistrations) {
        window.visualizerRegistrations = [];
    }
    window.visualizerRegistrations.push({
        id: '3d-bars',
        class: ThreeDBarVisualizer
    });
}

window.ThreeDBarVisualizer = ThreeDBarVisualizer;
